package cn.itsource.ymcc.userdetails;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.mapper.PermissionMapper;
import cn.itsource.ymcc.service.ILoginService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
@Component
@EnableWebSecurity
public class LoginUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private PermissionMapper permissionMapper;



    @Override
    public UserDetails loadUserByUsername(String username)  {
        Wrapper<Login> wrapper=new EntityWrapper<>();
        wrapper.eq("username",username);
        //根据username 拿到用户信息
        Login login = loginService.selectOne(wrapper);
        List<Permission> permissions=permissionMapper.loadPermissionsByLoginId(login.getId());
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission ->
                new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
        return new User(
                login.getUsername(),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                //权限
                authorities
        );




    }
}
